<template>
  <div class="create-task-page">
    <div class="create-task-header">
      <h1><i class="el-icon-plus"></i> 创建新任务</h1>
      <p class="subtitle">创建一个新的学习任务，设置详细信息和评分标准</p>
    </div>
    
    <el-card class="create-task-container" shadow="hover">
      <el-steps :active="activeStep" finish-status="success" simple class="task-steps">
        <el-step title="基本信息" icon="el-icon-document"></el-step>
        <el-step title="分组设置" icon="el-icon-user"></el-step>
        <el-step title="评分标准" icon="el-icon-star-on"></el-step>
        <el-step title="附件上传" icon="el-icon-upload"></el-step>
      </el-steps>
      
      <form @submit.prevent="handleSubmit" class="task-form">
        <!-- 步骤1：基本信息 -->
        <div v-show="activeStep === 0" class="step-content">
          <div class="form-group">
            <label for="title">任务标题：</label>
            <el-input 
              id="title" 
              v-model="currentTask.title" 
              placeholder="请输入任务标题" 
              prefix-icon="el-icon-edit"
              required
            />
          </div>
          
          <div class="form-group">
            <label for="description">任务描述：</label>
            <el-input 
              type="textarea" 
              id="description" 
              v-model="currentTask.description" 
              placeholder="请详细描述任务内容、目标和要求"
              :rows="5"
            />
          </div>
          
          <div class="form-group">
            <label for="deadline">任务截止日期：</label>
            <el-date-picker
              id="deadline"
              v-model="currentTask.deadline"
              type="datetime"
              placeholder="选择截止日期和时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              :picker-options="{disabledDate(time) { return time.getTime() < Date.now() - 8.64e7 }}"
              required
            />
          </div>
        </div>
        
        <!-- 步骤2：分组设置 -->
        <div v-show="activeStep === 1" class="step-content">
          <div class="form-group form-group-inline">
            <div class="form-item">
              <label for="min_group_size">最小组员数：</label>
              <el-input-number
                id="min_group_size"
                v-model="currentTask.min_group_size"
                :min="1"
                :max="10"
                controls-position="right"
                required
              />
            </div>
            
            <div class="form-item">
              <label for="max_group_size">最大组员数：</label>
              <el-input-number
                id="max_group_size"
                v-model="currentTask.max_group_size"
                :min="currentTask.min_group_size || 1"
                :max="20"
                controls-position="right"
                required
              />
            </div>
          </div>
          
          <div class="group-size-tips">
            <el-alert
              title="分组提示"
              type="info"
              description="设置合理的组员数量可以促进团队协作和任务分工，建议根据任务复杂度和学生人数进行设置。"
              :closable="false"
              show-icon
            >
            </el-alert>
          </div>
        </div>
        
        <!-- 步骤3：评分标准 -->
        <div v-show="activeStep === 2" class="step-content">
          <div class="form-group">
            <label for="scoring_criteria">评分标准：</label>
            <el-input
              type="textarea"
              id="scoring_criteria"
              v-model="currentTask.scoring_criteria"
              placeholder="请详细描述任务的评分标准、权重分配和评分要点"
              :rows="6"
            />
          </div>
          
          <div class="scoring-tips">
            <el-alert
              title="评分标准提示"
              type="info"
              description="明确的评分标准有助于学生理解任务要求和评价方式，建议包含质量评价、参与度、协作能力等多个维度。"
              :closable="false"
              show-icon
            >
            </el-alert>
          </div>
        </div>
        
        <!-- 步骤4：附件上传 -->
        <div v-show="activeStep === 3" class="step-content">
          <div class="form-group upload-area">
            <label for="sample">标准样例文件：</label>
            <el-upload
              class="upload-demo"
              drag
              action="#"
              :auto-upload="false"
              :on-change="handleFileUpload"
              :limit="1"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">拖拽文件到此处或 <em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">可上传任意类型文件作为任务样例或参考资料</div>
            </el-upload>
          </div>
        </div>
        
        <!-- 步骤控制按钮 -->
        <div class="step-controls">
          <el-button v-if="activeStep > 0" @click="prevStep" icon="el-icon-arrow-left">上一步</el-button>
          <el-button v-if="activeStep < 3" type="primary" @click="nextStep" icon="el-icon-arrow-right">下一步</el-button>
          <el-button v-if="activeStep === 3" type="success" native-type="submit" icon="el-icon-check">创建任务</el-button>
          <el-button type="info" @click="cancelCreate" icon="el-icon-close">取消</el-button>
        </div>
      </form>
    </el-card>
  </div>
</template>

<script>
import axios from "@/axiosInstance";
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
  name: "CreatTask",
  data() {
    return {
      activeStep: 0, // 当前步骤
      currentTask: {
        title: "",
        description: "",
        min_group_size: 2,
        max_group_size: 5,
        deadline: "",
        scoring_criteria: "",
        sample: null,
      },
      formRules: {
        title: [{ required: true, message: '请输入任务标题', trigger: 'blur' }],
        description: [{ required: true, message: '请输入任务描述', trigger: 'blur' }],
        deadline: [{ required: true, message: '请选择截止日期', trigger: 'change' }],
      },
      uploadTip: '上传标准样例文件',
      isSubmitting: false,
    };
  },
  methods: {
    // 步骤控制
    nextStep() {
      // 简单验证当前步骤
      if (this.activeStep === 0 && !this.currentTask.title) {
        ElMessage.warning('请至少填写任务标题');
        return;
      }
      if (this.activeStep === 1 && 
          (this.currentTask.min_group_size <= 0 || this.currentTask.max_group_size <= 0)) {
        ElMessage.warning('请设置有效的组员数量');
        return;
      }
      if (this.activeStep === 2 && !this.currentTask.scoring_criteria) {
        ElMessage.warning('请填写评分标准');
        return;
      }
      
      if (this.activeStep < 3) {
        this.activeStep++;
      }
    },
    prevStep() {
      if (this.activeStep > 0) {
        this.activeStep--;
      }
    },
    
    // 文件上传处理
    handleFileUpload(file) {
      // 使用el-upload时的处理方式
      this.currentTask.sample = file.raw;
      this.uploadTip = file.name;
      return false; // 阻止自动上传
    },
    
    // 表单提交
    async handleSubmit() {
      if (this.isSubmitting) return;
      this.isSubmitting = true;
      
      try {
        const user = this.$store.state.user || JSON.parse(localStorage.getItem("user"));
        if (!user || !user.user_id) {
          ElMessage.error("用户未登录或用户信息缺失");
          this.$router.push("/login");
          return;
        }

        const formData = new FormData();
        // 将 currentTask 字段添加到 formData
        Object.keys(this.currentTask).forEach((key) => {
          if (this.currentTask[key] !== null && this.currentTask[key] !== undefined) {
            formData.append(key, this.currentTask[key]);
          }
        });
        // 添加教师ID
        formData.append("teacher_id", user.user_id);

        // 发送请求到后端
        const response = await axios.post("/tasks/create/", formData, {
          headers: {"Content-Type": "multipart/form-data"},
        });

        if (response.data.status === "success") {
          ElMessage.success({
            message: "任务创建成功！",
            duration: 2000
          });
          setTimeout(() => {
            this.$router.push("/teacher");
          }, 2000);
        } else {
          console.error("任务创建失败:", response.data.message);
          ElMessage.error(`创建失败: ${response.data.message}`);
        }
      } catch (error) {
        console.error("任务创建错误:", error);
        ElMessage.error("创建失败，请稍后重试");
      } finally {
        this.isSubmitting = false;
      }
    },
    
    cancelCreate() {
      ElMessageBox.confirm(
        '确定要取消创建任务吗？已填写的内容将不会保存。',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        this.$router.push("/teacher");
      }).catch(() => {
        // 用户取消操作，不做任何处理
      });
    },
  },
};
</script>

<style scoped>
.create-task-page {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 30px 20px;
}

.create-task-header {
  text-align: center;
  margin-bottom: 30px;
  animation: fadeIn 0.8s ease-out;
}

.create-task-header h1 {
  font-size: 2.2rem;
  color: #409EFF;
  margin-bottom: 10px;
  font-weight: 600;
}

.subtitle {
  color: #606266;
  font-size: 1.1rem;
}

.create-task-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 30px;
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  background-color: #fff;
  animation: slideUp 0.5s ease-out;
}

.task-steps {
  margin-bottom: 40px;
}

.step-content {
  animation: fadeIn 0.4s ease-out;
  min-height: 300px;
}

.form-group {
  margin-bottom: 25px;
}

.form-group label {
  display: block;
  font-size: 1rem;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.form-group-inline {
  display: flex;
  gap: 20px;
}

.form-item {
  flex: 1;
}

.group-size-tips,
.scoring-tips {
  margin-top: 20px;
}

.upload-area {
  margin-top: 20px;
}

.step-controls {
  display: flex;
  justify-content: space-between;
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { transform: translateY(20px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .create-task-container {
    padding: 20px;
  }
  
  .form-group-inline {
    flex-direction: column;
    gap: 15px;
  }
  
  .create-task-header h1 {
    font-size: 1.8rem;
  }
}
</style>